package cn.com.css.taxInspection.util;

import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

import cn.com.css.taxInspection.common.constants.TaxConstants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.css.taxInspection.common.constants.Constants;
import cn.com.css.taxInspection.gt3.entity.DmGySwjgEntity;
import cn.com.css.taxInspection.gt3.service.DmGySwjgService;
import cn.com.css.taxInspection.system.service.impl.HttpSessionService;

@Component
public class TsBqUtils extends StringUtils {


    private static HttpSessionService httpSessionService;

    @Autowired
    public void setHttpSessionService(HttpSessionService httpSessionService) {
        TsBqUtils.httpSessionService = httpSessionService;
    }

    private static DmGySwjgService dmGySwjgService;

    @Autowired
    public void setDmGySwjgService(DmGySwjgService dmGySwjgService) {
        TsBqUtils.dmGySwjgService = dmGySwjgService;
    }

    /**
     * 删除list0 里面 list1
     *
     * @param list0 列表1
     * @param list1 列表2
     * @return listRemoveList
     */
    public static List<String> listRemoveList(List<String> list0, List<String> list1) {
        List<String> list = new ArrayList<>();
        if (isNull(list1)) {
            return list0;
        }
        for (String string0 : list0) {
            for (String string1 : list1) {
                if (!string0.equals(string1)) {
                    list.add(string0);
                }
            }
        }

        return list;
    }


    /**
     * 获取文件后缀名
     *
     * @param fileName 文件名
     * @return 后缀名
     */
    public static String getFileType(String fileName) {
        if (fileName != null && fileName.contains(".")) {
            return fileName.substring(fileName.lastIndexOf("."));
        }
        return "";
    }

    /**
     * 图片转base64字符串
     *
     * @param file 图片路径
     * @return String
     */
    @SuppressWarnings("restriction")
    public static String imageToBase64Str(MultipartFile file) {

        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = file.getInputStream();
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 加密
        sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
        return encoder.encode(data);
    }

    /**
     * object 转List
     *
     * @param obj
     * @param clazz
     * @return
     */
    public static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }

    /**
     * 获取uuid
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    @SuppressWarnings({"rawtypes"})
    public static boolean isNull(Object obj) {
        boolean isNullFlag = true;
        if (obj != null) {
            if (obj instanceof List<?>) {
                isNullFlag = isNull((List<?>) obj);
            } else if (obj instanceof Set<?>) {
                isNullFlag = isNull((Set<?>) obj);
            } else if (obj instanceof Object[]) {
                isNullFlag = isNull((Object[]) obj);
            } else if (obj instanceof Map) {
                isNullFlag = isNull((Map) obj);
            } else if (obj instanceof String) {
                isNullFlag = isNull((String) obj);
            } else {
                isNullFlag = false;
            }
        }
        return isNullFlag;
    }

    /**
     * 判断是否为空
     *
     * @param obj 输入
     * @return 结果
     * @author 作者 LIWEI
     */
    public static boolean isNotNull(Object obj) {
        return !isNull(obj);
    }

    /**
     * 判断列表是否为空
     *
     * @param list 传入一个列表
     * @return boolean是否为空
     */
    public static boolean isNull(List<?> list) {
        return list == null || list.isEmpty() || list.get(0) == null;
    }

    /**
     * 判断列表是否为空
     *
     * @param set set集合
     * @return boolean值
     */
    public static boolean isNull(Set<?> set) {
        return set == null || set.isEmpty();
    }

    /**
     * 判断数组是否为空
     *
     * @param objects 任何对象
     * @return boolean值
     */
    public static boolean isNull(Object[] objects) {
        return objects == null || objects.length == 0;
    }

    /**
     * 判断Map是否为空
     *
     * @param map map集合
     * @return boolean值
     */
    public static boolean isNull(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }

    /**
     * 判断字符串是否为空
     *
     * @param str 字符串
     * @return boolean值
     */
    public static boolean isNull(String str) {
        return str == null || str.trim().isEmpty() || "null".equalsIgnoreCase(str.trim());
    }

    /**
     * 获取数组长度
     *
     * @param list 列表
     * @return int 数值
     */
    public static int length(Collection<?> list) {
        return list == null ? 0 : list.size();
    }

    /**
     * 获取数组长度
     *
     * @param list 列表
     * @return int 数值
     */
    public static int length(List<?> list) {
        return list == null ? 0 : list.size();
    }

    /**
     * 获取数组长度
     *
     * @param objs object对象
     * @return int 数值
     */
    public static int length(Object[] objs) {
        return objs == null ? 0 : objs.length;
    }

    /**
     * 获取Map的长度
     *
     * @param map 集合
     * @return int 数值
     */
    public static int length(@SuppressWarnings("rawtypes") Map map) {
        return map == null ? 0 : map.size();
    }

    /**
     * 获取字符串长度
     *
     * @param str 字符串
     * @return int 数值
     */
    public static int length(String str) {
        return str == null ? 0 : str.length();
    }

    /**
     * 随机生成由数字、字母组成的N位验证码
     *
     * @return 返回一个字符串
     */
    public static String getCode(int n) {
        char arr[] = new char[n];
        int i = 0;
        while (i < n) {
            char ch = (char) (int) (Math.random() * 124);
            if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9') {
                arr[i++] = ch;
            }
        }
        // 将数组转为字符串
        return new String(arr);
    }

    /**
     * 两个Int相除
     *
     * @param n1
     * @param n2
     * @return
     */
    public static String divideInt(int n1, int n2) {
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        if (n1 == 0 && n2 == 0) {
            return "0%";
        } else if (n2 == 0) {
            return "100%";
        } else if (n1 == 0) {
            return "0%";
        }

        String result = numberFormat.format((float) n1 / (float) n2 * 100);
        return result + "%";
    }

    /**
     * 判断当前税务稽查为 省局、市局、县区局
     */
    public static String getTaxOrgLevel(String swjg) {
        if ("00000000".equals(swjg.substring(3, 11))) {
            return Constants.LEVEL_SHENGJU;
        }
        // 后面 6个0市局
        if ("000000".equals(swjg.substring(5, 11))) {
            return Constants.LEVEL_SHIJU;
        }
        // 后面 4个0县区局
        if ("0000".equals(swjg.substring(7, 11))) {
            return Constants.LEVEL_XIANQUJU;
        }
        return swjg;
    }

    /**
     * 判断List<String> 集合中是否存在重复
     * <p>
     * 集合中有重复元素 true 集合中没有重复元素 false
     *
     * @return
     */
    public static boolean isListStringrepeat(List<String> list) {

        Set<String> set = new HashSet<>(list); // 将list转换为set去重
        if (list.size() == set.size()) {
            return false;
        } else {
            return true;
        }

    }

    /**
     * @param taxOrg
     * @return
     */
    public static List<DmGySwjgEntity> recursionLevelTaxOrg(String taxOrg) {
        TsBqUtils utils = new TsBqUtils();
        // String currentDeptId = httpSessionService.getCurrentDeptId();
        List<DmGySwjgEntity> dmGySwjgList = utils.recursionTaxOrg(taxOrg, new ArrayList<>());
        return dmGySwjgList;
    }

    public List<DmGySwjgEntity> recursionTaxOrg(String taxOrg, List<DmGySwjgEntity> list) {
        LambdaQueryWrapper<DmGySwjgEntity> lambdaQuery = Wrappers.lambdaQuery();

        List<DmGySwjgEntity> swjgEntityList = dmGySwjgService
                .list(lambdaQuery.eq(DmGySwjgEntity::getSjswjgDm, taxOrg).eq(DmGySwjgEntity::getYxbz, "Y"));
        if (TsBqUtils.isNull(swjgEntityList)) {
            return list;
        } else {

            for (DmGySwjgEntity dmGySwjgEntity : swjgEntityList) {
                list.add(dmGySwjgEntity);
            }

            for (DmGySwjgEntity dmGySwjgEntity : swjgEntityList) {
                String swjgDm = dmGySwjgEntity.getSwjgDm();
                recursionTaxOrg(swjgDm, list);
            }
        }

        return list;
    }

    public static String getDataScopeByRolesId(String roles) {
        /**
         * jcj=当前登录人所在稽查局各个科室数据
         * all=各个稽查局的数据
         */
        String dataScope = "jcj";

        if (roles.contains(TaxConstants.SYSTEM_MGR_ID) || roles.contains(TaxConstants.DIRECTO_ID)
                || roles.contains(TaxConstants.SJLDG_ID)
                || roles.contains(TaxConstants.JCJLDG_ID)
        ) {
            dataScope = "all";
        } else if (roles.contains(TaxConstants.SECTION_CHIEF_ID)) {
            dataScope = "jck";
        }
        return dataScope;
    }

    public static Long calcMergeDays(String dateStr1, String dateStr2) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析日期字符串为LocalDate对象
        LocalDate date1 = LocalDate.parse(dateStr1, formatter);
        LocalDate date2 = LocalDate.parse(dateStr2, formatter);
        // 计算日期之间的天数差
        return ChronoUnit.DAYS.between(date1, date2);
    }

    public static String getCaseIdBySwjgDmAndLevel(String swjgDm, String level) {
        String caseId = "";
        if ("1".equals(level)) {//一类积案
            switch (swjgDm) {
                case "121010090":
                    caseId = "1753235180390457346";
                    break;
                case "121010091":
                    caseId = "4A83C7C7819843A6BC439E31E864FDDB";
                    break;
                case "121010092":
                    caseId = "1753235137625333761";
                    break;
                case "121010093":
                    caseId = "1753235212262973441";
                    break;
            }
        } else if ("2".equals(level)) {//二类积案
            switch (swjgDm) {
                case "121010090":
                    caseId = "1753235156424204289";
                    break;
                case "121010091":
                    caseId = "CD7144F1D8EF4F2A807B56BB6EF836C3";
                    break;
                case "121010092":
                    caseId = "1753235199331934210";
                    break;
                case "121010093":
                    caseId = "1753235225022046209";
                    break;
            }
        }
        return caseId;
    }

    public static String getAjhjMcByAjztDm(String ajztDm) {
        String mc = "";
        if (TsBqUtils.isNull(ajztDm)) {
            return "";
        } else {
            if (ajztDm.startsWith("2")) {
                mc = "检查环节";
            } else if (ajztDm.startsWith("3")) {
                mc = "审理环节";
            } else if (ajztDm.startsWith("4")) {
                mc = "执行环节";
            } else if (ajztDm.startsWith("5")) {
                mc = "终结";
            } else if (ajztDm.startsWith("6")) {
                mc = "案源撤销";
            } else if (ajztDm.startsWith("9")) {
                mc = "办结";
            }
            return mc;
        }
    }

    public static Date getSystemTime() {
        // 获取当前日期（只包含年月日，不包含时分秒）
        LocalDate today = LocalDate.now();

        // 将 LocalDate 转换为 Date 类型
        return Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }


    /**
     * 判断某个账号是否存在于字符串格式的账号列表中
     * @param accountListStr 形如 ["1699461822752550914", "1717700015853686785"]
     * @param targetId       要判断的账号
     * @return 是否存在
     */
    public static boolean containsAccount(String accountListStr, String targetId) {
        if (accountListStr == null || targetId == null) {
            return false;
        }

        // 去除中括号和双引号，然后按逗号切分
        String cleaned = accountListStr.replaceAll("[\\[\\]\"]", "");
        String[] idArray = cleaned.split(",\\s*");

        // 判断是否包含目标 ID
        for (String id : idArray) {
            if (id.equals(targetId)) {
                return true;
            }
        }

        return false;
    }

}
